package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.poisearch.PoiSearch.Query;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.AttendanceSummaryAdapter;
import com.isunland.managesystem.adapter.AttendanceSummaryAdapter.Callback;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.AttendanceDetail;
import com.isunland.managesystem.entity.AttendanceListOriginal;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

/**
 * 考勤打卡汇总列表
 *
 * @author wu
 */
public class AttendanceSummaryListFragment extends BaseListFragment
    implements OnPoiSearchListener, Callback {
  private static final int REQUEST_QUERY = 0;
  private String mjobNos;
  private AttendanceSummaryAdapter mAdapter;
  private String mBegindate;
  private String mEnddate;
  private String mStaffName;
  private TextView mNameTv;
  private TextView mStartDateTv;
  private TextView mEndDateTv;
  private int mPage = 1;// 请求第几页的数据.
  private String mTypeName;//打卡范围
  private String mTypeCode;//打卡范围
  private String mdeptCodes;
  private String arrJobNames;

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    if (NavUtils.getParentActivityName(getActivity()) != null) {
      ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.attendanceSummary);
    CurrentUser mCurrentUser = CurrentUser.newInstance(getActivity());
    mjobNos = mCurrentUser.getJobNumber();
    mStaffName = mCurrentUser.getRealName();
    mBegindate = MyDateUtil.getFirstDay();
    mEnddate = MyDateUtil.parseTimeToString(new Date(), MyDateUtil.TYPE_DATE);
    mTypeCode = "";
    mTypeName = "全部";
    mdeptCodes = "";
    arrJobNames = mStaffName;
    super.onCreate(savedInstanceState);
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    View header = getLayoutInflater(savedInstanceState).inflate(R.layout.header_sign, null, false);
    header.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View v) {
        startQuery();
      }
    });
    mNameTv = (TextView) header.findViewById(R.id.tv_name_signHeader);
    mStartDateTv = (TextView) header.findViewById(R.id.tv_startDate_signHeader);
    mEndDateTv = (TextView) header.findViewById(R.id.tv_endDate_signHeader);
    updateHeader();
    mListview.addHeaderView(header);
    mPullRefreshListView.setMode(Mode.BOTH);
  }

  //	@Override
  //	public void onListItemClick(ListView l, View v, int position, long id) {
  //		SwipeLayout swipe = ((SwipeLayout) (mListview.getChildAt(position - mListview.getFirstVisiblePosition())));
  //		swipe.toggle();
  //
  //
  ////		AttendanceDetail item = (AttendanceDetail) mAdapter.getItem(position - 2);
  ////		SwipeLayout swipe = ((SwipeLayout) (mListview.getChildAt(position - mListview.getFirstVisiblePosition())));
  ////
  ////		String name = item.getLocation();
  ////
  ////		if (swipe.getOpenStatus().equals(Status.Open)) {
  ////			if (TextUtils.isEmpty(name)) {
  ////
  ////				ToastUtil.show(R.string.noLocation);
  ////
  ////			} else {
  ////
  ////				searchByName(name);
  ////			}
  ////		}
  ////		swipe.toggle();
  //
  //		// String district = mCustomerDetail.getDistrictDesc();
  //
  //		// Intent intent = new Intent(getActivity(), LocationActivity.class);
  //		//
  //		// // intent.putExtra(LocationFragment.EXTRA_NAME, poi);
  //		// startActivity(intent);
  //		super.onListItemClick(l, v, position, id);
  //
  //	}

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_query, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  /**
   * 响应ActionBar中的按钮
   */
  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回按钮

      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_query:
        startQuery();
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }

    if (requestCode == REQUEST_QUERY && data != null) {
      mjobNos = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_JOB_NUMBER);
      mBegindate = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_BEGIN_DATE);
      mEnddate = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_END_DATE);
      mStaffName = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_STAFF_NAME);
      mTypeCode = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_TYPE_CODE);
      mTypeName = data.getStringExtra(AttendanceSummaryQueryFragment.REQUEST_TYPE_NAME);
      LogUtil.i("mjobNos=="
          + mjobNos
          + ",mEnddate=="
          + mEnddate
          + ",mEnddate=="
          + mEnddate
          + ",mType=="
          + mTypeCode);
      updateHeader();
      //mJobNos 中包含 " '"说明选择的是部门
      if (!TextUtils.isEmpty(mjobNos) && mjobNos.contains("'")) {
        arrJobNames = "";
        mdeptCodes = mjobNos;
      } else {
        arrJobNames = mStaffName;
        mdeptCodes = "";
      }
    }
    mPullRefreshListView.setMode(Mode.PULL_FROM_START);
    mPage = 1;
    volleyPost();
    mPullRefreshListView.setMode(Mode.BOTH);
    super.onActivityResult(requestCode, resultCode, data);
  }

  private void updateHeader() {
    mStartDateTv.setText(mBegindate);
    mEndDateTv.setText(mEnddate);
    mNameTv.setText(String.format("员工<%s>", mStaffName));
  }

  private void startQuery() {
    Intent intent = new Intent(getActivity(), AttendanceSummaryQueryActicity.class);
    intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_STAFF_NAME, mStaffName);
    intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_JOB_NUMBER, mjobNos);
    intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_BEGIN_DATE, mBegindate);
    intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_END_DATE, mEnddate);
    intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_TYPE_CODE, mTypeCode);
    intent.putExtra(AttendanceSummaryQueryFragment.REQUEST_TYPE_NAME, mTypeName);
    intent.putExtra(AttendanceSummaryQueryFragment.VALUE_FROM,
        AttendanceSummaryQueryFragment.ATTENT_SUMMARY);
    startActivityForResult(intent, REQUEST_QUERY);
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    params.put("curPage", mPage + "");
    params.put("pageSize", "20");
    params.put("type", "mobile");
    params.put("checkType", mTypeCode);
    params.put("begindate", mBegindate);
    params.put("enddate", mEnddate);
    params.put("arrJobNames", arrJobNames);//人员
    params.put("rangeDeptCodes", mdeptCodes);//部门
    return params;
  }

  @Override protected String setEmptyText() {
    return getResources().getString(R.string.currentMonth);
  }

  @Override public String getUrl() {

    return ApiConst.URL_SIGN_LIST;
  }

  @Override public void resolveResponse(String arg0) {
    AttendanceListOriginal summary = new Gson().fromJson(arg0, AttendanceListOriginal.class);
    List<AttendanceDetail> summaryDetail = summary.getList();
    if (summaryDetail != null && summaryDetail.size() == 0) {
      ToastUtil.show(R.string.that_is_all);
    }
    setAdapter(summaryDetail);
  }

  private void setAdapter(List<AttendanceDetail> summaryDetail) {
    if (summaryDetail == null) {
      summaryDetail = new ArrayList<>();
    }

    if (mAdapter == null) {
      mAdapter =
          new AttendanceSummaryAdapter(getActivity(), new ArrayList<AttendanceDetail>(), this);
      setListAdapter(mAdapter);
    }

    if (mPage == 1) {
      mAdapter.clear();
    }
    mAdapter.addAll(summaryDetail);
    ((AttendanceSummaryAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {

    Mode mode = refreshView.getCurrentMode();
    if (mode.equals(Mode.PULL_FROM_START)) {

      mPage = 1;
    }
    if (mode.equals(Mode.PULL_FROM_END)) {
      mPage++;
    }
    volleyPost();
  }

  // @Override
  // public void onListItemClick(ListView l, View v, int position, long id) {
  //
  // if (!mjobNos.equalsIgnoreCase(mCurrentUser.getJobNumber())) {
  // return;
  // }
  //
  // final AttendanceDetail item = mAdapter.getItem(position - 2);
  //
  // new AlertDialog.Builder(getActivity()).setTitle("删除考勤记录")
  // .setMessage("考勤记录删除后将不可恢复,是否确认?")
  // .setPositiveButton("确认", new DialogInterface.OnClickListener() {
  //
  // @Override
  // public void onClick(DialogInterface dialog, int which) {
  // volleypostDelete(item);
  // // mAdapter.remove(item);
  // // mAdapter.notifyDataSetChanged();
  // }
  //
  // }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
  //
  // @Override
  // public void onClick(DialogInterface dialog, int which) {
  // // Auto-generated method stub
  //
  // }
  // }).show();
  // super.onListItemClick(l, v, position, id);
  // }

  private void volleypostDelete(final AttendanceDetail item) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DEL_ATTENDANCE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", item.getId());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage result = new Gson().fromJson(arg0, SuccessMessage.class);
        if (result.getResult().equalsIgnoreCase(SuccessMessage.SUCCESS)) {
          ToastUtil.show(R.string.deleteSuccess);
          mAdapter.remove(item);
          mAdapter.notifyDataSetChanged();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.deleteFail);
      }
    });
  }

  @Override public void click(View v) {
    switch (v.getId()) {
      case R.id.ll_swipe://滑动查看标记
        int position = (Integer) v.getTag();

        final AttendanceDetail item = (AttendanceDetail) mAdapter.getItem(position);
        String name = item.getLocation();
        if (!TextUtils.isEmpty(name)) {
          ToastUtil.show(name);
        }
        if (!TextUtils.isEmpty(item.getLatitude()) && !TextUtils.isEmpty(item.getLongitude())) {
          //根据经纬度标记mark
          LogUtil.i("经纬度查询");
          seachByLatLng(item);
        } else {
          if (!TextUtils.isEmpty(name)) {
            //根据地址搜索
            LogUtil.i("地址查询");
            searchByName(name);
          } else {
            ToastUtil.show(R.string.noLocationInfo);
          }
        }

        break;
      case R.id.iv_photo://展示图片
        String filePath = (String) v.getTag();
        //String relativePath="100014_北京信普达系统工程有限公司/app/o_enterpriseforum_main/1F6E70A2-42AB-4CE2-A27B-E98D952765BF/4C81479F-76AD-4BF3-9CAA-EF61D744C0C5.jpg";
        Intent intent = new Intent(getActivity(), CompanyForumPictureActivity.class);
        intent.putExtra(CompanyForumPictureFragment.EXTRA_PICTUREA, filePath);
        intent.putExtra(CompanyForumPictureFragment.TYPE, CompanyForumPictureFragment.TYPEA);
        startActivity(intent);
        break;
    }
  }

  private void searchByName(String name) {
    // 搜索条件: 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域
    Query query = new PoiSearch.Query(name, "", "");
    query.setPageSize(10);
    query.setPageNum(0);
    // 初始化poiSearch对象
    PoiSearch poiSearch = new PoiSearch(getActivity(), query);
    // 设置回调数据的监听器
    poiSearch.setOnPoiSearchListener(this);
    MyUtils.showDialogLoading(getActivity());
    // 开始搜索
    poiSearch.searchPOIAsyn();
  }

  @Override public void onPoiSearched(PoiResult result, int rCode) {
    MyUtils.dismissDialog();
    // 返回码为0,代表成功
    //1000为成功，其他为失败
    try {
      if (rCode == 1000) {
        List<PoiItem> poiItems = result.getPois();
        PoiItem item = poiItems.get(0);
        Intent i = new Intent(getActivity(), LocationActivity.class);
        i.putExtra(LocationFragment.EXTRA_NAME, item);
        startActivity(i);
      } else if (rCode == 1804) {
        Toast.makeText(getActivity(), R.string.networkError, Toast.LENGTH_SHORT).show();
      } else if (rCode == 1008) {
        Toast.makeText(getActivity(), R.string.keyError, Toast.LENGTH_SHORT).show();
      } else {
        Toast.makeText(getActivity(), R.string.otherError, Toast.LENGTH_SHORT).show();
      }
    } catch (Exception e) {
      LogUtil.e("locationError", e);
      ToastUtil.show(R.string.noLocationInfo);
    }
  }

  @Override public void onPoiItemSearched(PoiItem poiItem, int i) {

  }

  private void seachByLatLng(AttendanceDetail content) {
    double lat = Double.parseDouble(content.getLatitude());
    double lon = Double.parseDouble(content.getLongitude());
    LatLonPoint latLonPoint = new LatLonPoint(lat, lon);
    PoiItem item = new PoiItem("", latLonPoint, content.getLocation(), "");
    Intent i = new Intent(getActivity(), LocationActivity.class);
    i.putExtra(LocationFragment.EXTRA_NAME, item);
    startActivity(i);
  }
}
